package com.svo.weitu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.svo.platform.picbrowser.PicBrowseActivity;
import com.svo.platform.utils.HttpUtil;
import com.svo.platform.utils.SvoToast;
import com.svo.weitu.R;
import com.svo.weitu.adapter.SearchAdapter;
import com.svo.weitu.util.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener {
	protected SwipeRefreshLayout swipeRefreshLayout;
	private RecyclerView listView;
	private Toolbar toolbar;
	private SearchAdapter adapter;
	private int page = 0;
	private final int NUM = 30;

	private List<JSONObject> datas = new ArrayList<>();
	private String url = "http://image.baidu.com/search/wisejsonala?tn=wisejsonala&ie=utf8&cur=result&word=%s&fr=&catename=&pn=%d&rn="+NUM+"&gsm=1e";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		toolbar = (Toolbar) findViewById(R.id.toolbar);
		setSupportActionBar(toolbar);
		toolbar.setNavigationIcon(R.mipmap.ic_back_normal);
		toolbar.setNavigationOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
		swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light, android.R.color.holo_orange_light,android.R.color.holo_green_light);
		swipeRefreshLayout.setOnRefreshListener(this);
		listView = (RecyclerView) findViewById(R.id.listView);
		RecyclerView.LayoutManager manager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
//		listView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
		listView.setLayoutManager(manager);

		adapter = new SearchAdapter(datas);
		adapter.setEnableLoadMore(false);
		adapter.setOnLoadMoreListener(this,listView);
		listView.setAdapter(adapter);
		adapter.setOnItemClickListener(this);
	}
	private String query;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.search, menu);
		final MenuItem menuItem = menu.findItem(R.id.action_search);//在菜单中找到对应控件的item
		final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
		searchView.setQueryHint("关键字");
		searchView.setIconified(false);
		searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextSubmit(String query) {
				if (TextUtils.isEmpty(query)) return false;
				SearchActivity.this.query = query;
				Utils.closeSoftKeyboard(SearchActivity.this);
				page = 1;
				if (adapter != null) {
					datas.clear();
					adapter.notifyDataSetChanged();
				}
				search();
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				return true;
			}
		});
		return super.onCreateOptionsMenu(menu);
	}


	public void search() {
		if (TextUtils.isEmpty(query)) {
			SvoToast.showHint(getApplicationContext(), "关键字不可为空", Toast.LENGTH_SHORT);
			return;
		}
		page = 1;
		try {
			HttpUtil.get(String.format(url, URLEncoder.encode(query, "utf-8"),NUM*(page-1)), null, new JsonHttpResponseHandler(){
				@Override
				public void onStart() {
					super.onStart();
					swipeRefreshLayout.setRefreshing(true);
				}
				@Override
				public void onSuccess(JSONObject json) {
					super.onSuccess(json);
					datas.clear();
					handData(json);
				}
				@Override
				public void onFinish() {
					super.onFinish();
					swipeRefreshLayout.setRefreshing(false);
				}
			});
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	protected void handData(JSONObject json) {
		try {
			JSONArray data = json.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject jo = data.getJSONObject(i);
				this.datas.add(jo);
			}
			for (int i = datas.size() - data.length(); i < datas.size(); i++) {
				adapter.notifyItemInserted(i);
			}
			if (data == null || data.length() < NUM) {
				adapter.setEnableLoadMore(false);
				adapter.loadMoreEnd();
			}else if (data.length() >= NUM) {
				adapter.setEnableLoadMore(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onRefresh() {
		search();
	}

	@Override
	public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
		ArrayList<String> pics = new ArrayList<>();
		ArrayList<String> picInfos = new ArrayList<>();
		for (JSONObject data : datas) {
			pics.add(data.optString("thumburl", ""));
			picInfos.add(data.optString("title", ""));
		}
		Intent intent = new Intent(this, PicBrowser.class);
		intent.putExtra(PicBrowseActivity.PICS, pics);
		intent.putExtra("picInfos", picInfos);
		intent.putExtra(PicBrowseActivity.CUR_POSITION, position);
		startActivity(intent);
	}

	@Override
	public void onLoadMoreRequested() {
		if (TextUtils.isEmpty(query)) {
			return;
		}
		page++;
		try {
			HttpUtil.get(String.format(url, URLEncoder.encode(query, "utf-8"),NUM*(page-1)), null, new JsonHttpResponseHandler(){
				@Override
				public void onStart() {
					super.onStart();
				}
				@Override
				public void onSuccess(JSONObject json) {
					super.onSuccess(json);
					handData(json);
				}
				@Override
				public void onFinish() {
					super.onFinish();
					adapter.loadMoreComplete();
				}
			});
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

}
